/*
 * Created on Feb 6, 2005
 * Created by dfhuynh
 */
package edu.mit.simile.longwell.corpus;

import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.hsqldb.jdbcDriver;

import com.hp.hpl.jena.db.DBConnection;
import com.hp.hpl.jena.db.ModelRDB;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.ModelMaker;
import com.hp.hpl.jena.shared.ReificationStyle;

/**
 * @author dfhuynh
 */
public class HSQLConnector implements Connector {
	/* (non-Javadoc)
	 * @see edu.mit.simile.corpus.IJdbcConnector#connect(java.util.Properties, java.lang.String)
	 */
	public Corpus connect(Properties properties, String corpusURI) {
		return new HSQLCorpus(
			corpusURI, new File(properties.getProperty("directory")));
	}

}

class HSQLCorpus extends Corpus {
	static private Logger s_logger = Logger.getLogger(HSQLCorpus.class);

	protected File			m_baseDir;

	protected ModelMaker	m_modelMaker;
	protected Connection	m_connection;

	public HSQLCorpus(String corpusURI, File baseDir) {
		super(corpusURI);

		m_baseDir = baseDir;
	}

	/* (non-Javadoc)
	 * @see edu.mit.simile.longwell.Corpus#dispose()
	 */
	public void dispose() {
		if (m_initialized) {
			if (m_modelMaker != null) {
				m_modelMaker.close();
				m_modelMaker = null;
			}
			if (m_connection != null) {
				try {
					m_connection.close();
				} catch (SQLException e) {
					s_logger.warn(
						"Error closing HSQLDB connection",
						e
					);
				}
				m_connection = null;
			}

			super.dispose();
		}
	}

	protected void createModel() {
		if (m_model != null) {
			return;
		}

		try {
			Properties properties = new Properties();
			properties.put("user", "sa");
			properties.put("password", "");

			m_connection = jdbcDriver.getConnection(
				"JDBC:hsqldb:file:" +
					new File(m_baseDir, "default")
						.getAbsolutePath().replace('\\', '/'),
				properties
			);

			m_modelMaker = ModelFactory.createModelRDBMaker(
				new DBConnection(m_connection, "HSQL"),
				ReificationStyle.Standard
			);

			m_model = m_modelMaker.createModel("default");

			((ModelRDB) m_model).setDoFastpath(false);
		} catch (SQLException e) {
			throw new InternalError(
				"Failed to create HSQL model on file " +
					m_baseDir.getAbsolutePath());
		}
	}
}
